/**
 * 通用腳本
 */

const isMobile = /Android|Windows Phone|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent) || /AppleWebKit.*Mobile/i.test(navigator.userAgent) || (/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(navigator.userAgent)) || window.innerWidth <= 768;

// 已登入 用戶菜單切換
let $userlogined = document.getElementById('j-user-logined');
if ($userlogined) {
    $userlogined.addEventListener('mouseover', function () {
        this.classList.add('active');
    });
    $userlogined.addEventListener('mouseout', function () {
        this.classList.remove('active');
    });
}


// 置頂浮動菜單
let $fixedMenu = document.getElementById('j-fixed-menu');
if ($fixedMenu) {
    let $fixedMenuButton = $fixedMenu.querySelector('button');

    $fixedMenuButton.addEventListener('click', function (e) {
        $fixedMenu.classList.toggle('active');
    }, false);
    $fixedMenuButton.addEventListener('mouseover', function () {
        this.innerHTML = !$fixedMenu.classList.contains('active') ? this.getAttribute('hover') : this.getAttribute('active');
    }, false);
    $fixedMenuButton.addEventListener('mouseout', function () {
        this.innerHTML = this.getAttribute('default');
    }, false);
}

let stopTouchMove = (e) => {
    e.preventDefault();
};
let onMobileControlToggle = (e) => {
    $mobileFixed.toggleClass('show');
    $body.toggleClass('hide');
    if ($mobileFixed.hasClass('show')) {
        let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
        $mobileFixed.css('top', scrollTop + 'px');
        document.addEventListener('touchmove', stopTouchMove, { passive: false });
    } else {
        onMobileControlClose(e);
    }
};
let onMobileControlClose = (e) => {
    $mobileFixed.removeClass('show');
    $body.removeClass('hide');
    document.removeEventListener('touchmove', stopTouchMove, { passive: false });
};

let $body = $(document.body);
let $mobileControl = $('#j-mobile-control').on('click', onMobileControlToggle);
let $mobileControlClose = $('#j-mobile-control-close').on('click', onMobileControlClose);
let $mobileUser = $('#j-mobile-user').on('click', onMobileControlToggle);
let $mobileFixed = $('#j-mobile-fixed');
let $mobileNav = $('#j-mobile-nav').on('click', 'li', function () {
    let $currentNav = $mobileNav.children('.mobile-nav-item.active');
    $(this).toggleClass('active');
    $currentNav && $currentNav.removeClass('active');
}).on('click', 'a', (e) => {
    e.stopPropagation();
});

$('#j-mobile-fixed-shade').on('click', onMobileControlClose);
